#!/usr/bin/env python
#-*- coding: UTF-8 -*-

import web
import urllib2
import json
import time

import config

class users:
	def __init__(self, db):
		self.sessions = {}
		self.db = db
		
		rows = self.db.select('users', what='uid,token,expire,name,icon,max_weibo_id,min_weibo_id')
		for r in rows:
			self.sessions[r['uid']] = dict(r)
		

	def __del__(self):
		pass

		
	def dump(self, ):
		for u in self.sessions:
			print type(u), self.sessions[u]

			
	def save(self, u):
		print 'users.save(%s)' % str(u)

		url = 'https://api.weibo.com/2/users/show.json?access_token=%s&uid=%d' % (u['token'], u['uid'])
		request = urllib2.urlopen(url)
		if request.getcode() != 200:
			print "failed to get the user info for %d" % (u['uid'])
			return

		result = json.JSONDecoder().decode(request.read())
		user = {'uid': result['id'],
				'token': u['token'],
				'expire': u['expire'],
				'name': result['screen_name'],
				'icon': result['profile_image_url'],
				'max_weibo_id': 0,
				'min_weibo_id': 0}
		self.sessions[user['uid']] = user

		vars = {'uid': u['uid']}
		result = self.db.select('users', vars, where='uid=$uid')
		if not result:
			self.db.insert('users', uid=user['uid'], token=user['token'], expire=user['expire'], name=user['name'], icon=user['icon'])
		else:
			self.db.update('users', vars, where='uid=$uid', token=user['token'], expire=user['expire'], name=user['name'], icon=user['icon'])


	def get(self, uid):
		#print 'users.get(%d)' % (uid)
		#dump()
		if not uid in self.sessions:
			raise Exception('no_valid_token')

		now = time.time()
		user = self.sessions[uid]
		if user['expire'] <= now:
			self.sessions.pop(uid, {})
			raise Exception('token_expire')
		
		return user

	def clear(self, uid):
		pass
